# coding=utf-8
import random
import requests
import json
import codecs


def get_file():
    key_list = []
    data_list = []
    with open('lang.json', encoding='utf-8') as a:
        # 读取文件
        result = json.load(a)
        for i in result:
            key_list.append(i)
            data_list.append(result[i])
    return key_list, data_list


class Translate:

    def __init__(self, source: str = 'zh-CN', target: str = 'en', proxy: str = 'http://127.0.0.1:7890', out_path='./'):
        self.keys, self.data = get_file()
        self.source = source
        self.target = target
        self.proxy = proxy
        self.out_path = out_path

    def get_result(self):
        if self.data is None:
            print('数据不能为空!')
            exit()
        print("开始翻译: 从 " + self.source + " -> " + self.target + ", 请等待...")
        url = "https://translate.google.com/translate_a/t?sl=" + self.source + "&tl=" + self.target + "&ie=UTF-8&oe=UTF-8&client=at&dj=1&format=html&v=1.0"
        user_agent = (
            f'GoogleTranslate/6.{random.randint(10, 100)}.0.06.{random.randint(111111111, 999999999)}'
            ' (Linux; U; Android {random.randint(5, 11)}; {base64.b64encode(str(random.random())['
            '2:].encode()).decode()}) '
        )
        headers = {
            'User-Agent': user_agent
        }
        data = {'q': self.data}
        proxies = {
            "http": self.proxy,
        }
        response = requests.post(url=url, data=data, headers=headers, proxies=proxies)
        resp_json = [i[1:-1] for i in response.text[1:-1].split(',')]
        if len(resp_json) != len(self.data):
            print('返回数据条数不匹配! 请求: %s 条, 返回: %s 条' % (len(self.data), len(resp_json)))
            exit()
        for i in range(len(resp_json)):
            print(self.keys[i] + " => " + resp_json[i])
        dictionary = dict(zip(self.keys, resp_json))
        path = self.out_path + self.target + '.json'
        print("翻译完成! 正在写入, 文件路径 -> " + path)
        with codecs.open(path, 'w', encoding='utf-8') as f:
            json.dump(dictionary, f, indent=4, ensure_ascii=False)
        print('写入完成!')

